<template>
  <div style="height: 100%">
    <template v-if="registerEnable && !registerAuth">
      <div class="register-provider">
        <BaseListForNoData :notice-msg="registerMessage"></BaseListForNoData>
      </div>
    </template>
    <template v-else-if="registerEnable && registerFinish">
      <div class="register-provider">
        <div class="register-provider-info register-provider-icon">
          <i v-if="isRegisterSuc" class="icon iconfont icon-yitongguo"></i>
          <i v-else class="icon iconfont icon-butongyi"></i>
        </div>
        <div class="register-provider-info register-provider-title">{{ `${isRegisterSuc ? $t('common.base.submitSuccess') : $t('common.base.loginFailed')}` }}</div>
        <div class="register-provider-info register-provider-desc">{{ registerMessage }}</div>
      </div>
    </template>
    <template v-else>
      <div class="service-manage">
        <div class="service-manage-edit-footer" v-show="!loadingPage">
          <div class="flex align-items-center service-title">{{ title }}</div>
          <div class="flex-x">
            <FormCellChange
              class="mar-r-8"
              :count="formCellCount"
              @update="
                e => {
                  formCellCount = e;
                }
              "
            ></FormCellChange>
            <el-button type="plain-third" :disabled="submitting" @click="cancel">{{ $t('common.base.cancel') }}</el-button>
            <el-button :disabled="submitting || pending" type="primary" @click="saveProvider">{{ $t('common.base.save') }}</el-button>
          </div>
        </div>
        <div class="service-manage-edit" v-show="!loadingPage" @click="close">
          <div class="service-manage-edit-main" :class="formCellCount > 1 ? 'bbx-form-cell-box bbx-normal-form-builder-cell' : ''">
            <form-builder ref="form" class="bbx-cell-form-builder" :form-cell-count="formCellCount" :form-status="id ? 'edit' : 'new'" :fields="formField" :value="providerValue" :extra-validations="extraValidations" mode="service_provider_edit" @update="update">
              <!--服务商编码-->
              <template slot="providerCode" slot-scope="{ field, value }">
                <form-item ref="providerCode" class="bbx-form-cell-item" :label="field.displayName" :prop-field="field" :prop-value="providerValue.providerCode" :validation="extraValidations.providerCode">
                  <form-text :field="field" v-model="providerValue[field.fieldName]" :placeholder="field.placeholder || ''" @update="update" />
                </form-item>
              </template>
              <!--授权地址-->
              <template slot="authorizeAddress" slot-scope="{ field, value }">
                <form-item ref="authorizeAddress" class="bbx-form-item bbx-form-item-view-padding" :label="field.displayName" :prop-field="field" :prop-value="providerValue.authorizeAddress" :validation="extraValidations.authorizeAddress">
                  <div class="bbx-table-new">
                    <el-button icon="el-icon-plus" class="add-subform-btn" @click="addAddress">{{ $t('common.base.addArea') }} </el-button>
                    <el-table :data="providerValue[field.fieldName]" :border="true" max-height="250" style="width: 100%" header-row-class-name="common-list-table-header__v2">
                      <el-table-column prop="province" :label="`${$t('common.base.province')}/${$t('common.base.municipality')}`" />
                      <el-table-column prop="city" :label="`${$t('common.base.district')}/${$t('common.base.town')}`" />
                      <el-table-column prop="dist" :label="`${$t('common.base.district')}/${$t('common.base.prefecture')}`" />
                      <el-table-column :label="$t('common.base.operation')">
                        <template slot-scope="scope">
                          <div class="color-primary just-cur-point" @click="removeChooseAddress(scope)">{{ $t('common.base.delete') }}</div>
                        </template>
                      </el-table-column>
                    </el-table>
                  </div>
                </form-item>
              </template>
              <!--授权工单类型-->
              <template slot="authorizeTask" slot-scope="{ field, value }">
                <form-item ref="authorizeTask" class="bbx-form-cell-item" :label="field.displayName" :prop-field="field" :prop-value="providerValue.authorizeTask" :validation="extraValidations.authorizeTask">
                  <biz-remote-select v-model="providerValue[field.fieldName]" :field="field" :multiple-limit="10" multiple cleared :remote-method="fetchTaskType" :placeholder="!field.isNull ? `[${$t('common.base.isRequire')}]${field.placeHolder}` : field.placeHolder" :computed-width-keys="['name']">
                    <div class="customer-template-option" slot="option" slot-scope="{ option }">
                      <span>{{ option.name }}</span>
                    </div>
                  </biz-remote-select>
                </form-item>
              </template>
              <!--授权产品目录-->
              <template slot="authorizeProduct" slot-scope="{ field, value }">
                <form-item ref="authorizeProduct" class="bbx-form-cell-item" :label="field.displayName" :prop-field="field" :prop-value="providerValue.authorizeProduct" :validation="extraValidations.authorizeProduct">
                  <biz-remote-select v-model="providerValue[field.fieldName]" :field="field" :multiple-limit="10" multiple cleared :remote-method="fetchProductType" :placeholder="!field.isNull ? `[${$t('common.base.isRequire')}]${field.placeHolder}` : field.placeHolder" :computed-width-keys="['label']">
                    <div class="customer-template-option" slot="option" slot-scope="{ option }">
                      <span>{{ option.name }}</span>
                    </div>
                  </biz-remote-select>
                </form-item>
              </template>
              <!--角色-->
              <template slot="role" slot-scope="{ field, value }">
                <form-item ref="role" class="bbx-form-cell-item" :label="field.displayName" :prop-field="field" :prop-value="providerValue.role" :validation="extraValidations.role">
                  <biz-remote-select v-model="providerValue[field.fieldName]" :field="field" cleared :remote-method="fetchRole" :placeholder="!field.isNull ? `[${$t('common.base.isRequire')}]${field.placeHolder}` : field.placeHolder" :computed-width-keys="['name']">
                    <div class="customer-template-option" slot="option" slot-scope="{ option }">
                      <span>{{ option.name }}</span>
                    </div>
                  </biz-remote-select>
                </form-item>
              </template>
              <!--授权有效期-->
              <template slot="validTime" slot-scope="{ field, value }">
                <form-item ref="validTime" class="bbx-form-cell-item" :label="field.displayName" :prop-field="field" :prop-value="providerValue.validTime" :validation="extraValidations.validTime">
                  <el-date-picker v-model="providerValue[field.fieldName]" type="daterange" align="right" unlink-panels range-separator="-" :start-placeholder="$t('common.base.startDate')" :end-placeholder="$t('common.base.endDate')" value-format="timestamp" :default-time="field.defaultValue ? field.defaultValue : ['00:00:00', '23:59:59']"></el-date-picker>
                </form-item>
              </template>
              <!--服务商名称-->
              <template slot="providerName" slot-scope="{ field, value }">
                <form-item ref="providerName" class="bbx-form-cell-item" :label="field.displayName" :prop-field="field" :prop-value="providerValue.providerName" :validation="extraValidations.providerName">
                  <form-text :field="field" v-model="providerValue[field.fieldName]" :placeholder="field.placeholder || ''" @update="update" />
                </form-item>
              </template>
              <!--公司名称-->
              <template slot="name" slot-scope="{ field, value }">
                <form-item v-if="notEditTaskNo" class="bbx-form-cell-item" :label="field.displayName" :is-not-null="!field.isNull">
                  <div class="form-servicerNo">{{ value }}</div>
                </form-item>
                <form-item v-else ref="name" class="bbx-form-cell-item" :label="field.displayName" :prop-field="field" :prop-value="providerValue.name" :validation="extraValidations.name">
                  <div style="display: flex; position: relative">
                    <el-input v-model="providerValue[field.fieldName]" :placeholder="field.placeholder || $t('common.placeholder.input2')" clearable @blur="iptBlur" @focus="iptFocus" @clear="iptClear"></el-input>
                    <div v-if="filterFlag" class="infinite-box">
                      <ul v-if="filterData.list.length > 0" v-infinite-scroll="load" infinite-scroll-distance="1" class="infinite-list" style="overflow: auto">
                        <li @click.stop.prevent="getItem(item)" v-for="(item, i) in filterData.list" :key="`${i}_${item.label}`">{{ item.label }}</li>
                      </ul>
                      <div v-else class="register-empty">{{ isEmptyLoading ? `${$t('common.base.loading')}...` : $t('common.base.tip.noData') }}</div>
                    </div>
                    <el-button @click.stop="btnFilter" type="plain-third" class="mar-l-10">{{ $t('common.base.queryCompany') }}</el-button>
                  </div>
                </form-item>
              </template>
              <!--纳税人识别号-->
              <template slot="taxNo" slot-scope="{ field, value }">
                <form-item class="bbx-form-cell-item" :is-not-null="!field.isNull" v-if="notEditTaskNo" :label="field.displayName">
                  <div class="form-servicerNo">{{ value }}</div>
                </form-item>
                <form-item class="bbx-form-cell-item" v-else ref="taxNo" :label="field.displayName" :prop-field="field" :prop-value="providerValue.taxNo" :validation="extraValidations.taxNo">
                  <el-input disabled v-model="providerValue[field.fieldName]" @update="update"></el-input>
                </form-item>
              </template>
              <!--营业执照-->
              <template slot="businessLicense" slot-scope="{ field, value }">
                <form-item class="bbx-form-cell-item" ref="businessLicense" :class="{ hide_box: providerValue.businessLicense.length === 1 }" :label="field.displayName" :prop-field="field" :prop-value="providerValue.businessLicense" :validation="extraValidations.businessLicense">
                  <el-upload action="string" list-type="picture-card" class="business-image" accept="image/*" :before-upload="onBeforeUploadImage" :on-preview="handlePictureCardPreview" :http-request="uploadImagePic" :on-remove="onRemovePic" :on-exceed="onExceedPic" :limit="1" :multiple="false" :file-list="providerValue.businessLicense">
                    <i class="el-icon-plus avatar-uploader-icon"></i>
                  </el-upload>
                </form-item>
              </template>
            </form-builder>
          </div>
        </div>
        <add-authorization-address ref="AuthorAddressRef" @updateAddress="updateAddress"></add-authorization-address>
        <el-dialog :title="$t('common.base.toast')" :visible.sync="createVisible" width="500px" @close="copyAccount(true, false)">
          <div class="flex copy-main">
            <div class="create-success-icon">
              <i class="icon iconfont icon-yitongguo"></i>
              <div class="name">{{ $t('common.base.tip.createSuccess') }}</div>
            </div>
            <div class="create-success-content">
              <div>{{ accountInfo.companyName }}</div>
              <div>
                {{ $t('common.base.principal') }} <span class="color-primary just-cur-point" @click="copyAccount(false)">{{ $t('common.base.clickCopy') }}</span>
              </div>
              <div>{{ $t('common.label.account') }}：{{ accountInfo.loginName }}</div>
              <div>{{ $t('common.base.initPassword') }}：{{ accountInfo.password }}</div>
            </div>
          </div>
          <span slot="footer" class="dialog-footer">
            <el-button type="primary" :disabled="pending" :loading="pending" @click="copyAccount(true)">{{ $t('common.base.completeAndCopy') }}</el-button>
          </span>
        </el-dialog>
      </div>
    </template>
  </div>
</template>

<script>
/* api */
import * as serviceProviderApi from '@src/api/serviceProviderApi';
/* util */
import * as FormUtil from '@src/component/form/util';
import { safeNewDate } from '@src/util/time';
import platform from '@src/platform';
import AddAuthorizationAddress from '../../component/AddAuthorizationAddress.vue';
import Uploader from 'packages/BaseUpload/uploader';

import { useCopy } from '@hooks/useElement';
import { COPY_TEXT_SUCCESS, COPY_TEXT_FIAL } from '@src/model/const/Alert';
import { openAccurateTab } from '@src/util/platform';
import { PageRoutesTypeEnum } from '@model/enum/PageRoutesEnum';
import { getRootWindowInitData } from '@src/util/window';
import { formatAddress, useFormTimezone } from 'pub-bbx-utils';
const { disposeFormSubmitTime } = useFormTimezone();
import FormCellChange from '@src/component/compomentV2/FormCellChange/index.vue';
export default {
  name: 'service-provider-edit',
  data() {
    let extraValidations = Object.freeze({
      ifRequired: type => {
        if (['providerName', 'taxNo'].includes(type)) return true;
        let field = this.formField.find(field => field.fieldName === type);
        return !!(field && !field.isNull);
      },
      /*服务商编码*/
      providerCode: async () => {
        let type = 'providerCode';
        // 不需要校验
        let result = this.type === 'register' ? true : await this.checkedCode(this.providerValue[type]); // 服务商注册不需要校验
        if (!result) return (this.$refs[type].errMessage = this.$t('common.validate.serviceProviderCodeRepeat'));
        if (!extraValidations.ifRequired(type)) return (this.$refs[type].errMessage = '');
        if (!this.providerValue[type]?.length) {
          return (this.$refs[type].errMessage = this.$t('common.validate.inputServiceProviderEncode'));
        }
        return (this.$refs[type].errMessage = '');
      },

      /* 授权工单类型 */
      authorizeTask: () => {
        let type = 'authorizeTask';
        // 不需要校验
        if (!extraValidations.ifRequired(type)) return false;
        if (!this.providerValue[type]?.length) {
          return (this.$refs[type].errMessage = this.$t('common.placeholder.selectAuthorizationTaskType'));
        }
        return (this.$refs[type].errMessage = '');
      },
      /* 授权工产品目录 */
      authorizeProduct: () => {
        let type = 'authorizeProduct';
        // 不需要校验
        if (!extraValidations.ifRequired(type)) return false;
        if (!this.providerValue[type]?.length) {
          return (this.$refs[type].errMessage = this.$t('common.placeholder.selectAuthorizationProductCatalog'));
        }
        return (this.$refs[type].errMessage = '');
      },
      /* 角色名称 */
      role: () => {
        let type = 'role';
        // 不需要校验
        if (!extraValidations.ifRequired(type)) return false;
        if (!this.providerValue[type]?.length) {
          return (this.$refs[type].errMessage = this.$t('common.placeholder.selectRole'));
        }
        return (this.$refs[type].errMessage = '');
      },
      /* 授权区域 */
      authorizeAddress: () => {
        let type = 'authorizeAddress';
        // 不需要校验
        if (!extraValidations.ifRequired(type)) return false;
        if (!this.providerValue[type]?.length) {
          return (this.$refs[type].errMessage = this.$t('common.placeholder.selectAuthorizationScope'));
        }
        return (this.$refs[type].errMessage = '');
      },
      /* 授权有效期 */
      validTime: () => {
        let type = 'validTime';
        // 不需要校验
        if (!extraValidations.ifRequired(type)) return false;
        if (!this.providerValue[type]?.length) {
          return (this.$refs[type].errMessage = this.$t('common.placeholder.selectAuthorizationIndate'));
        }
        return (this.$refs[type].errMessage = '');
      },
      /* 服务商名称 */
      providerName: async () => {
        let type = 'providerName';
        // 不需要校验
        let result = this.type === 'register' ? false : await this.checkedName(this.providerValue[type]); //注册服务商不需要校验服务商名称
        if (result) return (this.$refs[type].errMessage = this.$t('common.validate.serviceProviderNameRepeat'));
        if (!extraValidations.ifRequired(type)) return (this.$refs[type].errMessage = '');
        if (!this.providerValue[type]?.length) {
          return (this.$refs[type].errMessage = this.$t('common.validate.inputServiceProviderName'));
        }
        return (this.$refs[type].errMessage = '');
      },
      /* 纳税人识别号*/
      taxNo: async () => {
        let type = 'taxNo';
        let fieldTaxNO = this.formField.find(field => field.fieldName === type);
        // 不需要校验(已有纳税人识别号&无纳税人识别号字段-注册服务商)
        if (this.notEditTaskNo || !fieldTaxNO) return false;
        // 校验重复
        let result = await this.checkedTaxNo(this.providerValue[type]);
        if (result) return (this.$refs[type].errMessage = this.$t('common.validate.taxpayerCodeRepeat'));
        // 校验必填
        let isNull = fieldTaxNO?.isNull;
        if (isNull) return (this.$refs[type].errMessage = '');
        if (!this.providerValue[type]?.length) {
          return (this.$refs[type].errMessage = this.$t('common.validate.inputTaxpayerCode'));
        }
        return (this.$refs[type].errMessage = '');
      },
      /* 公司名称 */
      name: () => {
        if (this.notEditTaskNo) return false;
        let type = 'name';
        // 不需要校验
        if (!extraValidations.ifRequired(type)) return false;
        if (!this.providerValue[type]?.length) {
          return (this.$refs[type].errMessage = this.$t('common.validate.inputCompanyName'));
        }
        return (this.$refs[type].errMessage = '');
      },
      /* 营业执照 */
      businessLicense: () => {
        let type = 'businessLicense';
        // 不需要校验
        if (!extraValidations.ifRequired(type)) return false;
        if (!this.providerValue[type]?.length) {
          return (this.$refs[type].errMessage = this.$t('common.validate.selectBusinessLicense'));
        }
        return (this.$refs[type].errMessage = '');
      },
    });
    return {
      id: '',
      formField: [],
      providerValue: {},
      address: [],
      submitting: false,
      loadingPage: false,
      pending: false,
      extraValidations,
      editProvider: false, // 是否编辑服务商
      businessPic: [],
      // 企查查查询
      filterFlag: false,
      filterParams: {
        keyword: '',
        pageNum: 1,
        pageSize: 10,
      },
      filterData: {
        list: [],
      },
      isEmptyLoading: false,
      isTime: true,
      title: '',
      createVisible: false, // 服务商新建成功弹框
      accountInfo: {
        companyName: '',
        loginName: '',
        password: '',
      },
      tenantId: '', // 注册服务商跳转进来存储租户ID
      /*注册信息*/
      registerEnable: false,
      registerAuth: true, // 是否有注册权限
      registerFinish: false, // 注册完毕
      registerMessage: this.$t('serviceProvider.waitingApproval'),
      isRegisterSuc: true,
      /*注册信息*/
      type: 'create', // 判断进来服务商的类型：'approval'代表的是从审批进来的服务商审核，为空代表的是其他页面进来的服务商新建
      approvalId: '',
      titleType: {
        create: this.$t('common.pageTitle.pageServiceProviderCreate'),
        edit: this.$t('common.pageTitle.pageServiceProviderEdit'),
        approval: this.$t('common.base.approvalServiceProvider'),
        register: this.$t('common.base.registerServiceProvider'),
      },
      notEditTaskNo: false, // 在编辑状态下是否能编辑纳税人识别号
      formCellCount: 1,
    };
  },
  computed: {
    // 是否是服务商
    isProviderUser() {
      return getRootWindowInitData().isProviderUser || false;
    },
    // 0：钉钉端，1：自建，2：企微端
    tenantType() {
      return getRootWindowInitData().tenantType;
    },
  },
  components: {
    AddAuthorizationAddress,
    FormCellChange,
  },
  async mounted() {
    try {
      /*
      1.服务商新建页面
      2.内部人员审核服务商去新建(后缀type=approval)
      3.服务商注册页面(后缀type=register)
      4.内部人员编辑服务商页面(后缀type=edit)
      5.服务商编辑自己信息(后缀type=edit根据isProviderUser是否是服务商去区分是内部人员编辑服务商信息，还是服务商去编辑服务商信息)
      * */
      this.loadingPage = true;
      this.registerEnable = false;
      this.id = this.$getUrlObj(window).id || ''; // 用于编辑服务商用
      this.tenantId = this.$getUrlObj(window).tenantId || ''; // 用于注册服务商用
      if (this.$getUrlObj(window).type) this.type = this.$getUrlObj(window).type; // 用于审核服务商用
      this.approvalId = this.$getUrlObj(window).approvalId || ''; // 用于审核服务商用
      this.editProvider = this.type === 'edit';
      if (this.type === 'register') this.registerEnable = true;

      await this.getServiceManageTemplate(); // 获取服务商表单字段
      if (this.type === 'edit' || this.type === 'approval') {
        // 服务商编辑和审批需求查询
        await this.getProviderDataInfo();
      }

      this.title = this.titleType[this.type];
    } catch (error) {
      console.warn(error);
    } finally {
      this.loadingPage = false;
    }
  },
  methods: {
    /** ****公司名称********/
    async btnFilter() {
      if (!this.isTime) return;
      this.isTime = false;

      this.initIptData();
      this.filterFlag = true;

      await this.searchCustomer(this.filterParams);
    },
    iptBlur() {
      if (this.filterData.list.length > 0) {
        this.filterFlag = false;
      } else {
        this.filterFlag = false;
        this.initIptData();
      }
    },
    iptFocus() {
      // if(this.filterData.list.length > 0) this.filterFlag = true;
    },
    close() {
      this.filterFlag = false;
    },
    iptClear() {
      this.initIptData();
      this.providerValue.name = '';
      this.providerValue.taxNo = '';
      this.providerValue.legalPerson = '';
      this.filterParams.keyword = '';
      this.filterFlag = false;
    },
    initIptData() {
      this.filterData.list = [];
      this.filterParams.pageNum = 1;
    },
    getItem(e) {
      this.providerValue.name = e.label; // 公司名称
      this.providerValue.taxNo = e.value; // 纳税人识别号
      this.providerValue.legalPerson = e.operName; // 法定代表人
      this.filterParams.keyword = e.label;
      this.filterFlag = false;
    },
    async load() {
      if (this.filterData.list.length >= this.filterData.total) return;

      this.filterParams.pageNum++;
      await this.searchCustomer(this.filterParams);
    },
    async searchCustomer(params = {}) {
      this.isTime = true;
      if (!this.providerValue?.name) {
        this.filterFlag = false;
        return this.$message.warning(this.$t('common.validate.inputCompanyName'));
      }
      this.isEmptyLoading = true;
      if (this.providerValue?.name) {
        params.keyword = this.providerValue?.name || '';
      }
      if (this.type === 'register') {
        params.tenantId = this.tenantId;
      }
      try {
        let result = this.type === 'register' ? await serviceProviderApi.searchCompanyRegister(params) : await serviceProviderApi.searchCompany(params);
        this.isEmptyLoading = false;
        if (result.status !== 0) return;

        if (result.data) {
          result.data.list = result.data.list.map(product => ({
            label: product.name,
            value: product.creditCode || product.keyNo,
            ...product,
          }));

          const oldArr = this.filterData.list;
          const newArr = result.data.list;

          this.filterData = result.data;
          this.filterData.list = [...oldArr, ...newArr];
        }
      } catch (error) {
        console.warn('task-edit-form: searchCustomer -> error', error);
      }
    },

    // 校验服务商编码是否重复
    async checkedCode(code) {
      try {
        let data = {
          code,
        };
        if (this.editProvider) data.tenantProviderId = this.id;
        let res = await serviceProviderApi.codeRepeatCheck(data);
        if (res.success) return res.result;
      } catch (e) {
        console.error(e);
      }
    },

    /** ****公司名称********/
    // 校验服务商名称重复
    async checkedName(providerName) {
      try {
        let data = {
          providerName,
        };
        if (this.editProvider) data.tenantProviderId = this.id;
        let res = await serviceProviderApi.checkTenantProviderExist(data);
        if (res.success) return res.result;
      } catch (e) {
        console.error(e);
      }
    },
    // 校验纳税人识别号重复
    async checkedTaxNo(taxNo) {
      try {
        let res =
          this.type === 'register'
            ? await serviceProviderApi.checkProviderRegisterTaxNo({
                taxNo,
                tenantId: this.tenantId,
              })
            : await serviceProviderApi.checkProviderTaxNoExist(this.editProvider ? { taxNo, tenantProviderId: this.id } : { taxNo });
        if (res.success) return res.result;
      } catch (e) {
        console.error(e);
      }
    },
    // 获取服务商基本信息
    async getProviderDataInfo() {
      try {
        let res = this.type === 'approval' ? await serviceProviderApi.getProviderApproveDetail({ id: this.approvalId }) : await serviceProviderApi.getProviderDataInfo({ tenantProviderId: this.id });
        if (res.success && res.code === 0) {

          let providerInfoVO = res?.result?.providerInfoVO || {};
          // 处理富文本
          providerInfoVO.attribute = providerInfoVO.formVOList;
          providerInfoVO = await FormUtil.initRichTextContent(this.formField, providerInfoVO);
          let form = this.packToForm(this.formField, providerInfoVO);

          this.providerValue = FormUtil.initialize(this.formField, form);
          if (this.editProvider && this.providerValue?.taxNo) {
            this.notEditTaskNo = true;
          }
        }
      } catch (e) {
        console.error(e);
      }
    },
    // 获取新建字段
    async getServiceManageTemplate() {
      try {
        let res = {};
        if (this.tenantId) {
          // 服务商注册模版需要用服务商表单设计器和注册表单配置结合
          res = await serviceProviderApi.searchProviderRegisterConfig({ tenantId: this.tenantId });
        } else if (this.editProvider && this.isProviderUser) {
          // 服务商人员编辑自己的服务商信息需要用用服务商表单设计器和服务商修改表单配置结合
          res = await serviceProviderApi.searchEditConfig();
        } else {
          res = await serviceProviderApi.searchProviderConfig();
        }
        if (res.success) {
          if (this.registerEnable) this.registerAuth = true;
          const sortedFields = res.result.sort((a, b) => a.orderId - b.orderId) || [];
          this.formField = sortedFields.filter(item => item.fieldName !== 'status');

          this.formField.forEach(item => {
            if (item?.setting?.maxLength) item['maxlength'] = item.setting.maxLength;
            if (item.fieldName === 'certificate') {
              // 授权书
              item.tips = this.$t('common.placeholder.imgFormat', { format: 'jpg、png、jpeg、bmp', size: '10M', num: '3' });
              item.accept = 'image/*';
              item.limit = 3;
            }
            if (item.fieldName === 'provideQuality') item.formType = 'select';
            if (this.type === 'register' && (item.formType === 'attachment' || item.formType === 'imageDisplay')) {
              item.action = `/files/uploadNoAuth`;
              item.actionOptions = {
                tenantId: this.tenantId,
              };
              item.actionStorage = `/api/linkc/outside/linkc/v3c/ssp/event/remainingStorage?tenantId=${this.tenantId}`;
            }
            // 子表单的附件
            if (this.type === 'register' && item?.setting?.isSubForm) {
              item.subFormFieldList.forEach(itemSub => {
                if (itemSub.formType === 'attachment') {
                  itemSub.action = `/files/uploadNoAuth`;
                  itemSub.actionOptions = {
                    tenantId: this.tenantId,
                  };
                  itemSub.actionStorage = `/api/linkc/outside/linkc/v3c/ssp/event/remainingStorage?tenantId=${this.tenantId}`;
                }
              });
            }
          });
          this.providerValue = FormUtil.initialize(this.formField, {});
          this.providerValue['authorizeTask'] = [];
          this.providerValue['authorizeProduct'] = [];
          this.providerValue['authorizeAddress'] = [];
          this.providerValue['role'] = [];
        } else {
          if (this.registerEnable) {
            this.registerAuth = false;
            this.registerMessage = res?.message || this.$t('common.base.linkFailure');
            return;
          }
          this.$message.error(res.message);
        }
      } catch (e) {
        console.error(e);
      }
    },
    /** *********start 地址****************/
    addAddress(field) {
      this.$refs.AuthorAddressRef.openDialog(field.placeHolder);
    },
    removeChooseAddress(data) {
      this.providerValue['authorizeAddress'].splice(data.$index, 1);
    },
    updateAddress(val) {
      let { country = '', province = '', city = '', dist = '', address = '' } = val || {};
      let newAddress = {
        ...this.modelValue,
        country,
        province,
        city,
        dist,
        address,
      };
      this.providerValue['authorizeAddress'].push(newAddress);
    },
    /** *********end 地址****************/
    /* 查询工单类型*/
    async fetchTaskType(params = {}) {
      try {
        let { keyword, pageNum, pageSize } = params;
        const dataToSend = {
          keyword,
          pageNum,
          pageSize,
        };
        let res =
          this.type === 'register'
            ? await serviceProviderApi.getRegisterTaskTypeList({
                tenantId: this.tenantId,
                ...dataToSend,
              })
            : await serviceProviderApi.searchTaskTypeList(dataToSend);
        if (!res?.result) return;
        let data = {
          // 目前工单没有分页，做成假的分页，以后接口修改直接修改这里
          total: res.result.length,
          hasNextPage: false,
        };
        data.list = this.handleTagData(res?.result);
        return data;
      } catch (error) {
        console.error('search dept error', error);
      }
    },
    /* 查询产品类型*/
    async fetchProductType(params = {}) {
      try {
        let { keyword, pageNum, pageSize } = params;
        const dataToSend = {
          keyword,
          pageNum,
          pageSize,
        };
        // 服务商注册没有登陆信息接口需求传tenantId
        let res =
          this.type === 'register'
            ? await serviceProviderApi.getRegisterProductTypeList({
                tenantId: this.tenantId,
                ...dataToSend,
              })
            : await serviceProviderApi.searchProductTypeList(dataToSend);
        if (!res?.result?.list) return;
        let total = 1;
        if (pageNum === 1 && res?.result?.list.length === 0) {
          total = 0; // 目前产品类型查询接口不返回total,默认若查询不为空赋值total为1
        }
        res.result.list = this.handleTagData(res.result.list);
        res.result.total = total;
        return res.result;
      } catch (error) {
        console.error('search dept error', error);
      }
    },
    /* 查询角色*/
    async fetchRole(params = {}) {
      try {
        let { keyword } = params;
        const dataToSend = {
          roleName: keyword,
        };
        let res = await serviceProviderApi.getServiceRole(dataToSend);
        if (!res?.data) return;
        let data = {
          // 目前角色没有分页，做成假的分页，以后接口修改直接修改这里
          total: res.data.length,
          hasNextPage: false,
        };
        data.list = this.handleTagData(res?.data);
        return data;
      } catch (error) {
        console.error('search dept error', error);
      }
    },
    /** ****授权有效期******/
    updateValidTime(value) {
      if (Array.isArray(value) && value.length === 2) {
        return {
          validTime: safeNewDate(value[0]).getTime(),
          inalidTime: safeNewDate(value[1]).getTime(),
        };
      }
      return {};
    },
    /** ******营业执照**********/
    onBeforeUploadImage(file) {
      const isLt10M = file.size / 1024 / 1024 < 10;
      if (!isLt10M) {
        this.$message.error(this.$t('common.validate.imageLimit', { limit: '10M' }));
      }
      return isLt10M;
    },
    handlePictureCardPreview(file) {
      this.$previewElementImg(file.url);
    },
    onExceedPic() {
      this.$message.error(this.$t('common.validate.imgUploadLimit', { num: '1' }));
    },
    onRemovePic(o) {
      if (this.providerValue.businessLicense && this.providerValue.businessLicense.length) {
        this.$set(
          this.providerValue,
          'businessLicense',
          this.providerValue.businessLicense.filter(item => item.id != o.id)
        );
      }
    },
    uploadImagePic(param) {
      let action = this.type === 'register' ? '/files/uploadNoAuth' : '/files/upload';
      let actionStorage = this.type === 'register' ? `/api/linkc/outside/linkc/v3c/ssp/event/remainingStorage?tenantId=${this.tenantId}` : '/files/remainingStorage';
      Uploader.upload(param.file, action, { tenantId: this.tenantId }, actionStorage)
        .then(result => {
          if (result.status !== 0) {
            this.$message({
              message: `${result.message}`,
              duration: 1500,
              type: 'error',
            });
            return;
          }
          let file = result.data;
          let item = {
            uid: param.file.uid,
            id: file.id,
            filename: file.fileName,
            // 如果后端返回url,必须使用。如果后端不返回，需要拼接
            url: file.ossUrl || file.url || `/files/get?fileId=${file.id}`,
            fileSize: file.fileSizeStr,
          };
          this.$set(this.providerValue, 'businessLicense', [...this.providerValue.businessLicense, item]);
          this.businessPic.push(item);
        })
        .catch(err => {
          console.warn(err);
        });
    },
    /* biz-remote-select数据格式处理 */
    handleTagData(list) {
      let tagData = list.map(item => {
        return {
          label: (item && item.name) || '',
          value: (item && item.id.toString()) || '',
          id: (item && item.id.toString()) || '',
          name: (item && item.name) || '',
        };
      });
      return tagData;
    },
    update({ field, newValue, oldValue }) {
      let { fieldName, displayName, isSystem } = field;
      if (this.$appConfig.debug) {
        console.info(`[FormBuilder] ${displayName}(${fieldName}) : ${JSON.stringify(newValue)}`);
      }
      let value = this.providerValue;
      /* if(!value.attribute){
        value.attribute = {}
      }
      if(!isSystem){
        this.$set(value.attribute, fieldName, newValue);
      }*/
      this.$set(value, fieldName, newValue);
    },
    // 校验服务商
    async saveProvider() {
      this.submitting = true;
      try {
        // 校验
        const validated = await this.$refs.form.validate();
        if (!validated) {
          this.$message.error(this.$t('common.validate.noNull'));
          return Promise.reject('validate fail.');
        }
        this.toggleLoading();
        await this.submit();
      } catch (e) {
        console.error(e);
      } finally {
        this.submitting = false;
        this.toggleLoading(false);
      }
      // 保存成功以后弹框去提示初始账户密码
    },
    // 保存服务商
    async submit() {
      try {
        this.loadingPage = true;
        const submitForm = disposeFormSubmitTime(this.formField, this.providerValue); // 处理国际化日期时间数据转换
        let value = this.packSaveForm(this.formField, submitForm);
        if (this.editProvider) {
          value.push({
            fieldName: 'tenantProviderId',
            value: this.id,
            valueList: [],
            isSubForm: 1,
            isSystem: 1,
            valueType: 1,
          });
        }
        let data = {
          formList: value,
        };
        if (this.tenantId) {
          //服务商注册
          let resRegister = await serviceProviderApi.registerProvider({
            formList: value,
            tenantId: this.tenantId,
          });
          this.registerFinish = true;
          this.registerMessage = resRegister.success ? this.registerMessage : resRegister.message;
          this.isRegisterSuc = resRegister.success || false;
          return;
        } else if (this.type === 'approval') {
          // 审批新建服务商要多一个审批步骤
          data.source = 0;
          data.sourceId = this.approvalId;
        }
        let res = await serviceProviderApi.saveOrUpdateProviderInfo(data);
        if (this.tenantType === 1 && !this.editProvider && res.success) {
          // 只有独立段新建服务商的时候才生成一个主负责人
          // 新建服务商成功弹框
          if (res?.result?.mainCreateEnable) {
            this.accountInfo = res?.result;
            this.createVisible = true;
            return;
          }
        }
        platform.notification({
          type: res.success ? 'success' : 'error',
          title: res.success ? (this.editProvider ? this.$t('common.base.editServiceProviderSuccess') : this.$t('common.base.createServiceProviderSuccess')) : this.editProvider ? this.$t('common.base.editServiceProviderFailed') : this.$t('common.base.createServiceProviderFailed'),
          message: !res.success && res.message,
        });
        // 跳转到服务商列表页面
        this.closeAndOpenTab('PageServiceManage');
      } catch (e) {
        console.error(e);
      } finally {
        this.loadingPage = false;
      }
    },
    /** 将form对象转成服务商对象，用于提交表单 */
    packSaveForm(fields, form) {
      // 处理逻辑显示项
      /* 营业执照附件，授权区域，授权工单类型， 授权产品目录， 授权书上传多选, 资质证书，成功案例，标签，图片*/
      const fieldArray = ['businessLicense', 'authorizeAddress', 'authorizeTask', 'authorizeProduct', 'certificate', 'subSucCase', 'subCertifications', 'tagLabel', 'imageDisplay'];
      /* formType为人员，附件，多级菜单 多选*/
      const type = ['user', 'attachment', 'cascader'];
      let data = JSON.parse(JSON.stringify(form));
      let formData = [];
      fields
        .filter(f => f.formType !== 'info' && f.formType !== 'separator' && f.formType !== 'autograph' && f.formType !== 'location')
        .forEach(field => {
          let { fieldName, formType, setting, isSystem, displayName } = field;
          let value = data[fieldName];
          let fieldValue = {};
          // 人员单选
          if (formType === 'user' && !setting?.isMulti && Object.prototype.toString.call(value) === '[object Object]') {
            if (Object.keys(value).length) {
              value = value && [value];
            } else {
              value = [];
            }
          }
          // 地址
          if (formType === 'address') {
            // 转后台所需要字段
            if (value && Object.keys(value).length) {
              value.all = formatAddress(value, '');
              for (let key in value) {
                if (typeof value[key] === 'number') value[key] = value[key].toString(); // 转成字符串后后端
              }
            }
          }
          if (formType === 'authorizeAddress') {
            // 转后台所需要字段
            if (value && value.length) {
              value.forEach(item => {
                item.all = formatAddress(value, '');
              });
            }
          }
          if (fieldName === 'validTime') {
            // 授权有效期
            value = this.updateValidTime(value);
          }
          if (fieldName === 'role') {
            // 角色（接口需要对象）
            value = (value && value[0]) || null;
          }
          if (fieldName === 'tagLabel') {
            // 标签
            value = value.map(item => item.id);
          }

          if (fieldArray.find(item => item === fieldName) || (formType === 'select' && setting?.isMulti) || type.find(item => item === formType)) {
            fieldValue = {
              displayName,
              fieldName,
              valueList: value || [], // fix:value可能为空字符串
              isSubForm: setting?.isSubForm ? 1 : 0,
              isSystem,
              valueType: 2,
            };
          } else {
            fieldValue = {
              displayName,
              fieldName,
              value,
              isSubForm: 0,
              isSystem,
              valueType: 1,
            };
          }
          formData.push(fieldValue);
        });
      return formData;
    },
    /** 将服务商对象转成form表单，用于初始化表单 */
    packToForm(fields, data) {
      let proviver = {
        ...data.attribute,
      };
      fields.forEach(field => {
        let { fieldName, isSystem } = field;
        let value = data[fieldName] && JSON.parse(JSON.stringify(data[fieldName]));
        isSystem == 1 && (proviver[fieldName] = value);
        if (fieldName === 'authorizeTask') {
          proviver.authorizeTask = [];
          if (data?.authorizeTask && data?.authorizeTask.length) {
            proviver.authorizeTask = data?.authorizeTask.map(item => {
              return {
                label: item.name,
                value: item.id,
                ...item,
              };
            });
          }
        }
        if (fieldName === 'authorizeProduct') {
          proviver.authorizeProduct = [];
          if (data?.authorizeProduct && data?.authorizeProduct.length) {
            proviver.authorizeProduct = data?.authorizeProduct.map(item => {
              return {
                label: item.name,
                value: item.id,
                ...item,
              };
            });
          }
        }
        if (fieldName === 'role') {
          proviver.role = [];
          if (data?.role) {
            proviver.role = [
              {
                value: data.role.id,
                label: data.role.name,
                ...data.role,
              },
            ];
          }
        }
        if (fieldName === 'validTime' && data?.validTime) {
          proviver.validTime = [safeNewDate(data.validTime.validTime), safeNewDate(data.validTime.inalidTime)];
        }
        if (fieldName === 'authorizeAddress' && !proviver['authorizeAddress']) {
          proviver['authorizeAddress'] = [];
        }
      });
      return proviver;
    },
    closeAndOpenTab(type, key = '', params = '') {
      let id = window.frameElement.dataset.id;
      this.$platform.closeTab(id);

      let fromId = window.frameElement.getAttribute('id');
      // 跳转到服务商列表
      openAccurateTab({
        type: PageRoutesTypeEnum[type],
        key,
        params,
        reload: true,
        fromId,
      });
    },
    toggleLoading(loading = true) {
      this.pending = loading;
      this.loadingPage = loading;
    },
    cancel() {
      let id = window.frameElement.dataset.id;
      return this.$platform.closeTab(id);
    },
    // 复制账户密码
    copyAccount(closeEnable = true, isCopy = true) {
      if (isCopy) useCopy(`<div>${this.$t('common.label.account')}：${this.accountInfo?.loginName}</div><div>${this.$t('common.base.initPassword')}： ${this.accountInfo?.password}</div>`, COPY_TEXT_SUCCESS, COPY_TEXT_FIAL);
      if (closeEnable) {
        this.createVisible = false;
        // 跳转到服务商列表页面
        this.closeAndOpenTab('PageServiceManage');
      }
    },
  },
};
</script>

<style lang="scss">
@import './ProviderEditView.scss';
</style>
<style lang="scss" scoped>
::v-deep .el-table--border {
  border: 1px solid #ebeef5 !important;
}
.business-image {
  ::v-deep.el-upload-list__item {
    transition: none !important;
  }
  ::v-deep .el-upload--picture-card {
    width: 80px;
    height: 80px;
    line-height: 80px;
    margin-bottom: 6px;
    &:hover {
      border-color: $color-primary;
    }
  }
  ::v-deep .el-upload-list__item {
    width: 80px;
    height: 80px;
  }
}
.hide_box ::v-deep .el-upload--picture-card {
  display: none;
}
.infinite-box {
  width: calc(100% - 98px);
  position: absolute;
  left: 0;
  top: 35px;
  z-index: 999;
  background-color: #fff;

  border: 1px solid #e4e7ed;
  border-radius: 4px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
  box-sizing: border-box;
  margin: 5px 0;
}
.infinite-list {
  max-height: 274px;
  list-style: none;
  padding: 6px 0;
  margin: 0;
  box-sizing: border-box;
  background-color: #fff;
}
.infinite-list li {
  width: 100%;
  font-size: 14px;
  padding: 0 20px;
  position: relative;
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
  color: #606266;
  height: 34px;
  line-height: 34px;
  box-sizing: border-box;
  cursor: pointer;
}
.infinite-list li:hover {
  background-color: #f5f7fa;
}
.register-empty {
  padding: 10px 0;
  margin: 0;
  text-align: center;
  color: #999;
  font-size: 14px;
}
</style>
